package cn.iocoder.yudao.module.dify.util;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

public class JsonToMarkdownWriter {

    public static void writeJsonContentToMd(String jsonString, String filename) {
        try {
            // 解析JSON字符串
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(jsonString);

            // 获取output数组
            JsonNode outputArray = jsonNode.get("output");

            // 写入Markdown文件
            StringBuilder content = new StringBuilder();
            for (JsonNode node : outputArray) {
                content.append(node.asText()).append("\n");
            }

            Files.write(Paths.get(filename), content.toString().getBytes(StandardCharsets.UTF_8));
            System.out.println("成功写入Markdown文件: " + filename);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 从资源文件读取JSON内容并写入Markdown文件（兼容所有Java版本）
     *
     * @param resourcePath   资源文件路径
     * @param outputFilename 输出的Markdown文件名
     */
    public static void writeFromResource(String resourcePath, String outputFilename) {
        try (InputStream is = JsonToMarkdownWriter.class.getResourceAsStream(resourcePath)) {
            if (is == null) {
                throw new IOException("资源文件未找到: " + resourcePath);
            }
            String jsonString = readInputStreamAsString(is);
            writeJsonContentToMd(jsonString, outputFilename);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 从文件系统读取JSON文件并写入Markdown文件
     *
     * @param jsonFilePath   JSON文件路径
     * @param outputFilename 输出的Markdown文件名
     */
    public static void writeFromFile(String jsonFilePath, String outputFilename) {
        try {
            String jsonString = readFileAsString(jsonFilePath);
            writeJsonContentToMd(jsonString, outputFilename);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将InputStream读取为字符串（兼容所有Java版本）
     *
     * @param inputStream 输入流
     * @return 字符串内容
     * @throws IOException IO异常
     */
    private static String readInputStreamAsString(InputStream inputStream) throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[1024];

        while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }

        buffer.flush();
        byte[] byteArray = buffer.toByteArray();
        return new String(byteArray, StandardCharsets.UTF_8);
    }

    /**
     * 读取文件内容为字符串
     *
     * @param filePath 文件路径
     * @return 文件内容字符串
     * @throws IOException IO异常
     */
    private static String readFileAsString(String filePath) throws IOException {
        return new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);
    }

    /**
     * 使用StringBuilder构建长字符串（如果需要在代码中构造长字符串）
     *
     * @param parts 字符串片段数组
     * @return 完整的长字符串
     */
    public static String buildLongString(String[] parts) {
        StringBuilder sb = new StringBuilder();
        for (String part : parts) {
            sb.append(part);
        }
        return sb.toString();
    }

    /**
     * 解析JSON并写入Markdown文件
     */
    private static void parseAndWriteToMarkdown(String jsonString, String filename) throws IOException {
        // 解析JSON字符串
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(jsonString);

        // 获取output数组
        JsonNode outputArray = jsonNode.get("output");

        // 写入Markdown文件
        StringBuilder content = new StringBuilder();
        for (JsonNode node : outputArray) {
            content.append(node.asText()).append("\n\n");
        }

        Files.write(Paths.get(filename), content.toString().getBytes(StandardCharsets.UTF_8));
        System.out.println("成功写入Markdown文件: " + filename);
    }

    public static void main(String[] args) {
        // 方法2: 从文件系统读取
        JsonToMarkdownWriter.writeFromFile("C:\\Users\\xiezheng\\Desktop\\2022工\\puyuan-test\\翻译\\返回16.json", "C:\\Users\\xiezheng\\Desktop\\2022工\\puyuan-test\\翻译\\output16.md");

    }
}
